#include "Game.h"

Game::Game()
  : mIsNull(true),
  mForfeit(false),
  mForfeiter(""),
  mWinner("")
{
}

Game::Game(const QList<QString> &tokens)
    : mIsNull(false),
    mForfeit(false),
    mForfeiter(""),
    mWinner("")
{
  if (tokens.count() > 3)
  {
    mPlayer1 = tokens.at(0);
    mPlayer2 = tokens.at(1);
    if (tokens.at(2) == "F")
    {
      mForfeit = true;
      mForfeiter = mPlayer1;
    }
    else if (tokens.at(3) == "F")
    {
      mForfeit = true;
      mForfeiter = mPlayer2;
    }
    else
    {
      for (int i(2); i<tokens.count(); ++i)
      {
        QString turnstr(tokens.at(i));
        bool bag(false);
        turnstr.replace("\r\n", "");
        bag = turnstr.contains("'");
        turnstr.replace("'", "");
        addTurn(turnstr.toInt(), bag);
      }
    }
  }
}

const QString& Game::player1() const
{
  return mPlayer1;
}

const QString& Game::player2() const
{
  return mPlayer2;
}

const QList<Game::Turn>& Game::turns() const
{
  return mTurns;
}

bool Game::isNull() const
{
  return mIsNull;
}

bool Game::forfeit() const
{
  return mForfeit;
}

const QString& Game::forfeiter() const
{
  return mForfeiter;
}

const QString& Game::winner() const
{
  return mWinner;
}

const QString& Game::loser() const
{
  return mLoser;
}

void Game::setPlayers(const QString &player1, const QString &player2)
{
  mPlayer1 = player1;
  mPlayer2 = player2;
  mWinner = "";
  mIsNull = false;
}

bool Game::isOver() const
{
  bool cancel(true);
  int previous(-1);
  foreach (Turn t, mTurns)
  {
    if ((int)t.points < previous && !cancel) return true;
    else if ((int)t.points == previous) cancel = true;
    else cancel = false;
    previous = t.points;
  }
  return false;
}

bool Game::addTurn(unsigned int points, bool bagWasMade)
{
  mTurns.push_back(Turn(points, bagWasMade));
  if (isOver())
  {
    mWinner = mTurns.count()%2==1?mPlayer2:mPlayer1;
    mLoser = mTurns.count()%2==1?mPlayer1:mPlayer2;
    return true;
  }
  return false;
}

bool Game::editTurn(int turn, unsigned int points, bool bagWasmade)
{
  if (mTurns.count() > turn)
  {
    mTurns.replace(turn, Turn(points, bagWasmade));
    if (isOver())
    {
      if ((turn+1)%2==1) ++turn;
      while (mTurns.count() > turn+1) mTurns.pop_back();
      mWinner = mTurns.count()%2==1?mPlayer2:mPlayer1;
      mLoser = mTurns.count()%2==1?mPlayer1:mPlayer2;
      return true;
    }
  }
  return false;
}

QString Game::toString() const
{
  QString ret(mPlayer1 + " vs " + mPlayer2 + ": ");
  foreach (Turn t, mTurns)
  {
    ret += QString(" ") + QString::number(t.points) + ((t.bagWasMade?"'":""));
  }
  return ret;
}
